//
//  PGDetailViewController.m
//  PhotographicGuide
//
//  Created by indream on 13-2-10.
//  Copyright (c) 2013年 indream. All rights reserved.
//

#import "PGDetailViewController.h"
#import "PGPhotographicViewController.h"
#import "PGWebViewController.h"
#import "PGMediaViewController.h"
#import "PGDetailCell.h"
#import "PGArticleManager.h"
#import "MobClick.h"
#import "SBJson/SBJson.h"
#import "PGShopViewController.h"
#import "PGProductManager.h"
@interface PGDetailViewController (){
    BOOL _hasDevices;
    BOOL _hasCommend;
    BOOL _hasTeach;
}

@end

static NSString* NOTIFICATION_PRODUCT_TABLE_REFRESH = @"__NOTIFICATION_PRODUCT_TABLE_REFRESH__";
@implementation PGDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(id)init{
    self = [super init];
    if(self){
        
        
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadTable:) name:NOTIFICATION_PRODUCT_TABLE_REFRESH object:nil];
    [PGArticleManager sharedManager].currentArticleId = _articleId;
    [MobClick beginLogPageView:[NSString stringWithFormat:@"detail=%d",_articleId]];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:NOTIFICATION_PRODUCT_TABLE_REFRESH object:nil];
    [MobClick endLogPageView:[NSString stringWithFormat:@"detail=%d",_articleId]];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.shareView.isDetail = YES;
    _article = [[PGArticleManager sharedManager]articleWithID:_articleId];
    _titleLabel.text = _article.name;
    [[PGArticleManager sharedManager]addArticleView:_articleId];
    
    NSString *json = _article.devices;
    SBJsonParser *parser = [[SBJsonParser alloc]init];
    NSDictionary*dict = [parser objectWithString:json];
    _hasDevices = dict!=nil;
    _hasCommend = NO;
    _hasTeach = [_article.teachUrl componentsSeparatedByString:@"http://"].count>1;
    if([[UIDevice currentDevice] userInterfaceIdiom] ==UIUserInterfaceIdiomPad){
        [[PGProductManager sharedManager]requestWithTag:_article.tag];
    }
    UISwipeGestureRecognizer *swiper = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeHandle:)];
    [self.view addGestureRecognizer:swiper];
    // Do any additional setup after loading the view from its nib.
}
-(void)swipeHandle:(UISwipeGestureRecognizer*)gesture{
    if(gesture.direction==UISwipeGestureRecognizerDirectionRight){
        [self backHandle:nil];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)reloadTable:(NSNotification*)notification{
//    NSLog(@"%@",notification.userInfo);
    if(notification.userInfo){
        if ([[notification.userInfo objectForKey:@"code"]intValue]==0) {
            NSArray *list = [notification.userInfo objectForKey:@"list"];
            if(list){
                if(list.count>0){
                    _hasCommend = YES;
                    self.product = [list objectAtIndex:0];
                    [_tableView reloadData];
                }
            }
        }
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1+(_hasTeach?1:0)+(_hasDevices?1:0)+(_hasCommend?1:0);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
        return indexPath.row==0?428.0:44.0;
    }else{
        return indexPath.row==0?735.0:88.0;
    }
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell;
    switch (indexPath.row) {
        case 0:
        {
            cell = [self generalDetailItemCell:tableView];
            
            break;
        }
        case 1:
        {
            if(_hasDevices){
                cell = [self generalInfoItemCell:tableView withFlag:0];
            }else{
                if(_hasTeach){
                    cell = [self generalInfoItemCell:tableView withFlag:1];
                }else{
                    if(_hasCommend){
                        cell = [self generalInfoItemCell:tableView withFlag:2];
                    }
                }
            }
            
            break;
        }
        case 2:{
            if(_hasDevices){
                if(_hasTeach){
                    cell = [self generalInfoItemCell:tableView withFlag:1];
                }else{
                    if(_hasCommend){
                        cell = [self generalInfoItemCell:tableView withFlag:2];
                    }
                }
            }else{
                if(_hasCommend){
                    cell = [self generalInfoItemCell:tableView withFlag:2];
                }
            }
        }
        case 3:{
            if(_hasCommend){
                cell = [self generalInfoItemCell:tableView withFlag:2];
            }
        }
        default:
        {
            
        }
            break;
    }
    return cell;
}
-(UITableViewCell*)generalInfoItemCell:(UITableView*)tableView withFlag:(int)flag{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PGDetailItemCell"];
    if (cell == nil) {
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
            [[NSBundle mainBundle] loadNibNamed:@"PGDetailCell" owner:self options:nil];
        }else{
            [[NSBundle mainBundle] loadNibNamed:@"PGDetailCell_iPad" owner:self options:nil];
        }
        cell = _tvDetailItemCell;
        self.tvDetailItemCell = nil;
    }
    [(PGDetailItemCell*)cell iconView].image = [UIImage imageNamed:flag==0?@"park_details_icon_info.png":(flag==1?@"tray_cell_icon_photo.png":@"scope_icon.png")];
    [(PGDetailItemCell*)cell titleLabel].text = flag==0?@"拍摄设备和参数":(flag==1?@"我也要拍":[_product objectForKey:@"name"]);
    return cell;
}
-(UITableViewCell*)generalDetailItemCell:(UITableView*)tableView{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PGDetailCell"];
    if (cell == nil) {
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
            [[NSBundle mainBundle] loadNibNamed:@"PGDetailCell" owner:self options:nil];
        }else{
            [[NSBundle mainBundle] loadNibNamed:@"PGDetailCell_iPad" owner:self options:nil];
        }
        cell = _tvCell;
        self.tvCell = nil;
    }
    PGDetailCell*detailCell = (PGDetailCell*)cell;
    [detailCell loadImage:_article.imageMiddle];
    detailCell.descriptionLabel.text = _article.desc;
    CGSize size;
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
        size = [detailCell.descriptionLabel.text sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:CGSizeMake(233.0,111.0) lineBreakMode:UILineBreakModeCharacterWrap];
    }else{
        size = [detailCell.descriptionLabel.text sizeWithFont:[UIFont systemFontOfSize:18.0] constrainedToSize:CGSizeMake(383.0,130.0) lineBreakMode:UILineBreakModeCharacterWrap];
    }
    CGRect rect = detailCell.descriptionLabel.frame;
    rect.size.width = size.width;
    rect.size.height = size.height;
    detailCell.descriptionLabel.frame = rect;
    detailCell.titleLabel.text = _article.name;
    detailCell.authorLabel.text = [NSString stringWithFormat:@"%@",_article.author];
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
        size = [detailCell.authorLabel.text sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:CGSizeMake(216.0,21.0) lineBreakMode:UILineBreakModeCharacterWrap];
    }else{
        size = [detailCell.authorLabel.text sizeWithFont:[UIFont systemFontOfSize:18.0] constrainedToSize:CGSizeMake(416.0,21.0) lineBreakMode:UILineBreakModeCharacterWrap];
    }
    rect = detailCell.authorButton.frame;
    rect.origin.x = detailCell.authorLabel.frame.origin.x+size.width+5.0;
    detailCell.authorButton.frame = rect;
    detailCell.authorUrl = _article.authorUrl;
    detailCell.favorsLabel.text = [NSString stringWithFormat:@"%d人喜欢",_article.favors.intValue];
    detailCell.viewsLabel.text = [NSString stringWithFormat:@"%d人浏览",_article.views.intValue];
    detailCell.navigationController = self.navigationController;
    return detailCell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==1){
        if(_hasDevices){
            [self openDevices];
        }else{
            if(_hasTeach){
                [self openTeachURL];
            }else{
                if (_hasCommend) {
                    [self openCommendURL];
                }
            }
        }
    }
    if(indexPath.row==2){
        
        if(_hasDevices){
            if(_hasTeach){
                [self openTeachURL];
            }else{
                if (_hasCommend) {
                    [self openCommendURL];
                }
            }
        }else{
            if (_hasCommend) {
                [self openCommendURL];
            }
        }
    }
    if(indexPath.row==3){
        if (_hasCommend) {
            [self openCommendURL];
        }
    }
}
-(void)openDevices{
    PGPhotographicViewController *controller = [[PGPhotographicViewController alloc]initWithNibName:[[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone?@"PGPhotographicViewController":@"PGPhotographicViewController_iPad" bundle:nil];
    controller.articleId = _articleId;
    [self.navigationController pushViewController:controller animated:YES];
}
-(void)openTeachURL{
    PGWebViewController *controller = [[PGWebViewController alloc]init];
    controller.title = @"我也要拍";
    controller.url = _article.teachUrl;
    [self.navigationController pushViewController:controller animated:YES];
}
-(void)openCommendURL{
    PGWebViewController *controller = [[PGWebViewController alloc]initWithNibName:@"PGShopViewController_iPad" bundle:nil];
    controller.url = [_product objectForKey:@"url"];
    controller.title = [_product objectForKey:@"name"];
    [self.navigationController pushViewController:controller animated:YES];
}
- (IBAction)backHandle:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)findHandle:(id)sender {
    [self addShareView:_articleId];
}

- (IBAction)clickLargeHandle:(id)sender {
    PGMediaViewController *controller = [[PGMediaViewController alloc]init];
    //controller.imageId = _imageId;
    controller.articleId = _articleId;
    controller.title = _article.name;
    controller.url = _article.imageLarge;
    [self.navigationController pushViewController:controller animated:YES];
}
- (void)viewDidUnload {
    [self setTvCell:nil];
    [self setTvDetailItemCell:nil];
    [self setTableView:nil];
    [self setTitleLabel:nil];
    [super viewDidUnload];
}
@end
